#!python
# -*- coding:UTF-8 -*-
# from openGauss dbmind opengauss_exporter


def wipe_off_password(command):
    command = "******"
    return command

def set_proc_title(name: str):
    new_name = name.encode('ascii', 'replace')

    try:
        import ctypes
        libc = ctypes.CDLL('libc.so.6')
        progname = ctypes.c_char_p.in_dll(libc, '__progname_full')
        with open('/proc/self/cmdline') as fp:
            old_progname_len = len(fp.readline())
        if old_progname_len > len(new_name):
            # padding blank chars
            new_name += b' ' * (old_progname_len - len(new_name))

        # for `ps` command:
        # Environment variables are already copied to Python app zone.
        # We can get environment variables by `os.environ` module,
        # so we can ignore the destroying from the following action.
        libc.strcpy(progname, ctypes.c_char_p(new_name))
        # for `top` command and `/proc/self/comm`:
        buff = ctypes.create_string_buffer(len(new_name) + 1)
        buff.value = new_name
        libc.prctl(15, ctypes.byref(buff), 0, 0, 0)
    except Exception as e:
        print('An error (%s) occured while setting the process name.', e)

def wipe_off_password_from_proc_title(db_connection_string):
    """
    Removes the password from the database connection string from the process title
    @param db_connection_string: database connection string
    @return: None
    """
    wiped_url = wipe_off_password(db_connection_string)
    with open('/proc/self/cmdline') as fp:
        cmdline = fp.readline().replace('\x00', ' ')
    wiped_cmdline = cmdline.replace(db_connection_string, wiped_url)
    set_proc_title(wiped_cmdline)



